define([
  'jquery',
  'underscore',
  'views/View',
  'views/upload/UploadView',
  'views/upload/PhotoAlbumModal',
  'hbs!template/upload/upload-preview'
], function($, _, View, UploadView, PhotoAlbumModal, template){
  
  var UploadPreview = UploadView.extend({
    events: {
      "click input[name=selection]":  "selection",
      "click img.thumbnail":          "modalPreview"
    },
    
    initialize: function(options){
      UploadView.prototype.initialize(options);
      this.template = template;
      this.data = options.data;
      if(this.data) {
        this.file = this.data.file;
      }
      _.bindAll(this,
                'uploadProgress');
    },
    
    render: function() {
      $(this.el).html(this.template(this.model.toJSON()));
      return this;
    },

    selection: function() {
      var selected = this.model.get('selected');
      this.model.set({selected: !selected});

      this.render();
    },

    isSelected: function() {
      return this.model.get('selected');
    },

    upload: function() {
      console.log("Upload preview: " + this.isSelected());
      if(this.isSelected()) {
        this.uploadFile(this.model.get('file'));
      }
    },

    uploadProgress: function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        //console.log($(".uploadProgress", this.el));
        var progressBar = $(".uploadProgress", this.el);
        if(progressBar) {
          progressBar.attr('value', percentComplete);
        }
        //$("#uploadProgress").attr("value", percentComplete);
      }
      else {
        console.log("Fail to get the percent from evt.");
      }
    },

    modalPreview: function() {
      console.log("Modal preview calling");
      var position = this.collection.indexOf(this.model);
      this.collection.pagination.setOffset(position);
      var modal = new PhotoAlbumModal({collection: this.collection});
      modal.render();
    }
  });

  return UploadPreview;
});